package com.liuya.safe.entitle.controller;

import com.liuya.base.BaseController;
import com.liuya.common.exception.EntityExistException;
import com.liuya.common.SpringUtils;
import com.liuya.common.WebUtil;
import com.liuya.safe.entitle.handler.DecisionEntitlementHandler;
import com.liuya.safe.entitle.service.EntitleManagerService;
import com.liuya.safe.entitle.service.PrivilegeManagerService;
import com.liuya.safe.model.SafeBusinessData;
import com.liuya.safe.model.SafePrivilege;
import com.liuya.safe.model.SafeUserCategory;
import com.liuya.safe.policy.service.BusinessDataManagerService;
import com.liuya.safe.policy.service.QueryManagerService;
import com.liuya.safe.policy.service.UserCategoryManagerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

import java.util.Collection;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.liuya.safe.model.SafeDecisionEntitlement;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * 权限管理
 * @author liuya
 * @date 20160826
 */
@Controller
@Api(value = "权限管理", description = "权限管理")
@RequestMapping(value = "decisionEntitlement")
public class DecisionEntitlementContrller extends BaseController {
    private static final Log log = LogFactory.getLog(DecisionEntitlementContrller.class);

    @ApiOperation(value = "跳转到主页")
//    @RequiresPermissions("sys.nonRolePriviMng.decision")
    @RequestMapping(value = "/decision")
    public String decision(HttpServletRequest req, HttpServletResponse rep, ModelMap modelMap){
        DecisionEntitlementHandler handler = getHandler(req);
        modelMap.addAttribute("handler", handler);

        return "privilege/decisionEntitlement";
    }

    @ApiOperation(value = "跳转到主页")
//    @RequiresPermissions("sys.nonRolePriviMng.loadEntitlements")
    @RequestMapping(value = "/loadEntitlements")
    public String loadEntitlements(HttpServletRequest req, HttpServletResponse rep, ModelMap modelMap){
        DecisionEntitlementHandler handler = getHandler(req);
        modelMap.addAttribute("handler", handler);

        return "privilege/decisionEntitlementTable";
    }

    @ApiOperation(value = "跳转到主页")
//    @RequiresPermissions("sys.nonRolePriviMng.getEntitlement")
    @RequestMapping(value = "/getEntitlement")
    public String getEntitlement(HttpServletRequest req, HttpServletResponse rep, ModelMap modelMap){

        DecisionEntitlementHandler handler = getHandler(req);
        modelMap.addAttribute("handler", handler);

        int index = WebUtil.getIntParameter(req, "index", -23);
        if (index >= 0) {
            SafeDecisionEntitlement entitlement = (SafeDecisionEntitlement) handler.getDecisionEntitlements().get(index);
            req.setAttribute("entitlement", entitlement);
        }

        return "privilege/editDecisionEntitlement";
    }

    @ApiOperation(value = "跳转到主页")
//    @RequiresPermissions("sys.nonRolePriviMng.returnMain")
    @RequestMapping(value = "/returnMain")
    public String returnMain(HttpServletRequest req, HttpServletResponse rep, ModelMap modelMap){
        DecisionEntitlementHandler handler = getHandler(req);
        modelMap.addAttribute("handler", handler);

        String gotoUrl = "./nonRolePriviMng/openTree.do";
        if (handler.getPrivilege().getType() == 0) {
            gotoUrl = "./privilegeMng/openTree.do";
        }

        String key = getHandlerAttributeKey(req);
        req.getSession().removeAttribute(key);

        return "redirect:/" + gotoUrl;
    }

    @ApiOperation(value = "跳转到主页")
//    @RequiresPermissions("sys.nonRolePriviMng.addEntitle")
    @RequestMapping(value = "/addEntitle")
    @ResponseBody
    public boolean addEntitle(HttpServletRequest req, HttpServletResponse rep, ModelMap modelMap){
        DecisionEntitlementHandler handler = getHandler(req);
        modelMap.addAttribute("handler", handler);
        SafeDecisionEntitlement entitle = getDecisionEntitlement(req);
        handler.addEntitle(entitle);
        updateHandler(req);
        return true;
    }

    @ApiOperation(value = "跳转到主页")
//    @RequiresPermissions("sys.nonRolePriviMng.editEntitle")
    @RequestMapping(value = "/editEntitle")
    @ResponseBody
    public boolean editEntitle(HttpServletRequest req, HttpServletResponse rep, ModelMap modelMap){
        DecisionEntitlementHandler handler = getHandler(req);
        modelMap.addAttribute("handler", handler);
        int index = WebUtil.getIntParameter(req, "index", 0);
        SafeDecisionEntitlement entitle = getDecisionEntitlement(req);
        handler.updateEntitle(index, entitle);
        updateHandler(req);
        return true;
    }

    @ApiOperation(value = "跳转到主页")
//    @RequiresPermissions("sys.nonRolePriviMng.moveEntitle")
    @RequestMapping(value = "/moveEntitle")
    @ResponseBody
    public boolean moveEntitle(HttpServletRequest req, HttpServletResponse rep, ModelMap modelMap){
        DecisionEntitlementHandler handler = getHandler(req);
        modelMap.addAttribute("handler", handler);

        int index = WebUtil.getIntParameter(req, "index", 0);
        String direct = req.getParameter("direct");
        handler.moveEntitle(index, direct);
        updateHandler(req);

        return true;
    }

    @ApiOperation(value = "跳转到主页")
//    @RequiresPermissions("sys.nonRolePriviMng.deleteEntitle")
    @RequestMapping(value = "/deleteEntitle")
    @ResponseBody
    public boolean deleteEntitle(HttpServletRequest req, HttpServletResponse rep, ModelMap modelMap){
        DecisionEntitlementHandler handler = getHandler(req);
        modelMap.addAttribute("handler", handler);

        int index = WebUtil.getIntParameter(req, "index", 0);
        handler.deleteEntitle(index);
        updateHandler(req);

        return true;
    }

    @ApiOperation(value = "跳转到主页")
//    @RequiresPermissions("sys.nonRolePriviMng.save")
    @RequestMapping(value = "/save")
    @ResponseBody
    public boolean save(HttpServletRequest req, HttpServletResponse rep, ModelMap modelMap){
        DecisionEntitlementHandler handler = getHandler(req);
        modelMap.addAttribute("handler", handler);
        boolean result = false;
        try {
            handler.save();
            result = true;
        } catch (EntityExistException e) {
            log.error("", e);
        }
        // clean session
        String key = getHandlerAttributeKey(req);
        req.getSession().removeAttribute(key);

        return result;
    }

    public DecisionEntitlementHandler createHandler(HttpServletRequest req) {
        String id = WebUtil.getStringParameter(req, "id", "-23");

        PrivilegeManagerService privilegeManager = (PrivilegeManagerService) SpringUtils.getBean("privilegeManagerService");
        EntitleManagerService entitleManager = (EntitleManagerService) SpringUtils.getBean("entitleManagerService");
        QueryManagerService queryMng = (QueryManagerService) SpringUtils.getBean("queryManagerService");

        SafePrivilege pvlg = privilegeManager.getPrivilege(id);
        Collection entitlements = entitleManager.getDecisionEntitlements(id);

        if (log.isDebugEnabled()) {
            log.debug("id=" + id + ", name=" + pvlg.getName());
        }

        return new DecisionEntitlementHandler(pvlg, entitlements);
    }

    public String getHandlerAttributeKey(HttpServletRequest req) {
        int id = WebUtil.getIntParameter(req, "id", 0);
        return "_$safeDecisionEntitlement_" + id;
    }

    private DecisionEntitlementHandler getHandler(HttpServletRequest req) {
        String oper = req.getParameter("oper");
        String key = getHandlerAttributeKey(req);
        DecisionEntitlementHandler handler = null;
        Object obj = req.getSession().getAttribute(key);

        if (obj == null || "loadFresh".equals(oper)) {
            handler = createHandler(req);

            // save into session, will be removed when policy is saved
            req.getSession().setAttribute(key, handler);
        } else {
            handler = (DecisionEntitlementHandler) obj;
        }

        return handler;
    }

    private void updateHandler(HttpServletRequest req){
        String key = getHandlerAttributeKey(req);
        req.getSession().setAttribute(key, getHandler(req));
    }

    private SafeDecisionEntitlement getDecisionEntitlement(HttpServletRequest req) {
        String denyReason = req.getParameter("denyReason");
        String effect = req.getParameter("effect");
        String bdId = WebUtil.getStringParameter(req, "bdId", "-23");
        String ucId = WebUtil.getStringParameter(req, "ucId", "-23");
        String id = WebUtil.getStringParameter(req, "id", "-23");

        BusinessDataManagerService bdManager = (BusinessDataManagerService) SpringUtils.getBean("businessDataManagerService");
        SafeBusinessData bd = bdManager.getBusinessData(bdId);
        UserCategoryManagerService userCategoryManager = (UserCategoryManagerService) SpringUtils.getBean("userCategoryManagerService");
        SafeUserCategory userCategory = userCategoryManager.getUserCategory(ucId);

        SafeDecisionEntitlement entitle = new SafeDecisionEntitlement();
        entitle.setBusinessData(bd);
        entitle.setBusinessDataId(bdId);
        entitle.setDenyReason(denyReason);
        entitle.setPrivilegeId(id);
        entitle.setEffect(effect);
        entitle.setUserCategoryId(ucId);
        entitle.setUserCategory(userCategory);

        return entitle;
    }
}

